

// -------百度地图API调用相关功能开始--------//
var map = new BMap.Map("map_box");    // 创建Map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 5);  // 初始化地图,设置中心点坐标和地图级别
//添加地图类型控件
map.addControl(new BMap.MapTypeControl({
  mapTypes:[
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
      ]}));   
// map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true);
map.enableAutoResize();
var geoc = new BMap.Geocoder();  //地理位置逆解析

// 百度地图地址搜索功能
var local = new BMap.LocalSearch(map, {
    renderOptions:{map: map}
  });
var search_map=function(addr){
  console.log(addr)
  local.search(addr);
}


//地图打点功能函数
var bd_map_marker_obj_list={};
var add_marker_bdmap=function(obj,marker_kind='default'){
  console.log(obj,marker_kind)
  var icon_dict={'building':'/static/show_icon/normal.png','camera':'/static/show_icon/camera.png',
                 'scanner':'/static/show_icon/scanner.png','Person':'/static/show_icon/green_man.png',
                 'Car':'/static/show_icon/default_car.png','Asset':'/static/show_icon/middle.png',
                 'default':'/static/show_icon/track_button.png','asset':'/static/show_icon/middle.png'}

  var obj_name,user_kind,key_field,point;
  if(marker_kind=='device'){
    point=new BMap.Point(obj.lng,obj.lat)
    obj_name=obj.user_name
    key_field='device_id'
    if(obj.user_detail!='0'){
      obj_name=obj.user_detail.name
      user_kind=obj.user_detail.user_kind
    }
  }else{
    var location=[0,0]
    if(marker_kind=='asset'){
      if(obj.device_id!=''){
        location=eval('('+obj.device_id.dynamic+')')
        location=[location.lng,location.lat]
      }
    }else{
      var location= eval('('+obj.position+')')
      if(location!==0){
        location= location.location.split(',')
      }
    }
    
    point=new BMap.Point(location[0],location[1])
    obj_name=obj.name
    key_field='name'
    if(marker_kind=='scanner' | marker_kind=='camera'){
      key_field='device_id'
    }
    user_kind=marker_kind
  }
  
  // 地址逆解析
  get_bdmap_addr(point,obj[key_field])

  var icon_show=icon_dict[user_kind]
  if(obj.show_icon!=null && obj.show_icon!='0'){
    icon_show='/static/show_icon/'+obj.show_icon+'.png'
  }
  if(obj_name==''){
    obj_name=obj[key_field]
  }
  // myIcon = new BMap.Icon(icon_show, new BMap.Size(72,144),{anchor : new BMap.Size(27, 13),imageSize:new BMap.Size(22, 30)});
  myIcon = new BMap.Icon(icon_show, new BMap.Size(72,144),{imageSize:new BMap.Size(30, 30)});
  var marker = new BMap.Marker(point,{icon:myIcon});
  marker.self_detail=obj
  marker.user_kind=user_kind
  // 点击响应事件
  marker.addEventListener('click', function (e) {
    open_info_window(e.target.self_detail,e.point,e.target.user_kind)
  })
  map.addOverlay(marker);//加载定位点
  bd_map_marker_obj_list[obj[key_field]]=marker;//汇集添加到地图的marker，方便移除和其他操作
  marker.setTitle(obj[key_field]);//设置标题
  var lb_html='<button class="layui-btn layui-btn-sm" style="border-radius:10px">'+obj_name+'</button>'
  var mylabel=new BMap.Label(lb_html,{offset:new BMap.Size(0,-35)});
  mylabel.setStyle({border:'0',borderRadius:"10px"})
  marker.setLabel(mylabel);
  // open_info_window(obj,point,user_kind)
  map.centerAndZoom(point, 18);
};

//百度地图添加设备marker覆盖物功能函数

var add_device_marker_bdmap=function(obj){
  
  var model=obj.model
  var user_detail=obj.user_detail
  var obj_name=obj.user_name
  var device_id=obj.device_id
  var marker_icon='/static/show_icon/'+user_detail.icon+'.png'
  var point
  point=new BMap.Point(obj.lng,obj.lat)
  // 判断设备是否上传wg84的卫星递定位经纬度
  var wgs84=dev_model_objs[model].datakind.wgs84
  console.log(wgs84)
  if(wgs84=='无'){
    return
  }
  // 地址逆解析
  get_bdmap_addr(point,device_id)
  if(obj_name==''){
    obj_name=obj['device_id']
  }
  myIcon = new BMap.Icon(marker_icon, new BMap.Size(72,144),{anchor : new BMap.Size(27, 13),imageSize:new BMap.Size(22, 30)});
  // myIcon = new BMap.Icon(marker_icon, new BMap.Size(72,144),{imageSize:new BMap.Size(30, 30)});
  var marker = new BMap.Marker(point,{icon:myIcon});
  marker.self_detail=obj
  // 点击响应事件
  marker.addEventListener('click', function (e) {
    open_info_window(e.target.self_detail,e.point,'device')
  })
  map.addOverlay(marker);//加载定位点
  bd_map_marker_obj_list[obj['device_id']]=marker;//汇集添加到地图的marker，方便移除和其他操作
  marker.setTitle(obj['device_id']);//设置标题
  var lb_html='<button class="layui-btn layui-btn-sm" style="border-radius:10px">'+obj_name+'</button>'
  var mylabel=new BMap.Label(lb_html,{offset:new BMap.Size(0,-35)});
  mylabel.setStyle({border:'0',borderRadius:"10px"})
  marker.setLabel(mylabel);
  open_device_infowindow(obj,point)
  map.centerAndZoom(point, 18);
};


var open_info_window=function(obj,point,kind){
  if (kind=='building' | kind=='camera' | kind=='scanner'){
    static_marker_inforwindow(obj,point,kind)
  }else if(kind=='device'){
    open_device_infowindow(obj,point)
  }
}


//删除地图定位点
var remove_marker_bdmap=function(key_field){
  var m=bd_map_marker_obj_list[key_field];
  map.removeOverlay(m);
  map.closeInfoWindow();
};

// 地址逆解析，从经纬度变成文字地址，百度接口
var all_addr_obj={};
var get_bdmap_addr=function(pt,key_field){
      var location
      geoc.getLocation(pt, function(rs){
      var addComp = rs.address
      if(rs.surroundingPois.length!=0){
        // console.log(rs)
         location=addComp+','+rs.surroundingPois[0]['title']
         all_addr_obj[key_field]=location;   
      }else{
         location=addComp
         all_addr_obj[key_field]=location;
      }
    });
  };


//设备定位点信息窗展示功能
var open_device_infowindow=function(gps,point){
  // console.log(gps)
  var bds_num=gps.dynamic.bds_num,param1,param2,param3,param4,blood_pres,gps_num=gps.dynamic.gps_num,rssi=gps.dynamic.rssi;
    var dev_kind='0'
    if(gps.dynamic.receive_port!='0'){
      dev_kind=gps.dynamic.receive_port[1]
    }
    var dev_loca=all_addr_obj[gps.device_id]
    // console.log(dev_loca)
    if(dev_loca=='' && gps.dynamic.track_type!=='0'){
      wifi_lbs={'wifi':gps.dynamic.wifi,'lbs':gps.dynamic.lbs}
      dev_loca='<button class="layui-btn layui-btn-xs" onclick="get_wifi_lbs_addr('+gps.device_id+',\''+gps.dynamic.track_type+'\')">点击解析'+gps.dynamic.track_type+'地址</button>'
    }

    // var status_list=['acc_off', 'ante_ok', 'undefence', 'normal','online','sleep']
    status_dict={'undefence':'未设防', 
                  'normal':'正常',
                  'online':'<font color="green">在</font>',
                  'sleep':'<font color="blue">休</font>',
                  'sos_alarm':'<font color="red">sos</font>',
                  'offline':'<font color="black">离</font>'}
    if(bds_num==null){
      bds_num='0'
    }
    if(gps_num==null){
      gps_num='0'
    }
    // var stop_time=(eval('('+gps.stop_time+')')['stop_time']/60).toFixed(0)
    var stop_time='0'
    var g_status;
    var status=''
    if(gps.on_off_line=='online'){
      g_status='1'
    }else{
      g_status='0'
    }
    // 状态信息
    for(var i=0;i<gps.status.length;i++){
      if(gps.status[i] in status_dict){
        status+=status_dict[gps.status[i]]+' '
      }else{
        status+=gps.status[i]+' '
      }
    }
    
    blood_pres=''
    if(gps.dynamic.blood_pres!='0'){
      blood_pres=eval('('+gps.dynamic.blood_pres+')')
      blood_pres='高：'+blood_pres['h_pres']+','+'低：'+blood_pres['l_pres']
    }
    heart_rate=''
    if(gps.dynamic.heart_rate!='0'){
      heart_rate=gps.dynamic.heart_rate
    }

    // 绑定的用户信息
    var user_detail=gps.user_detail;
    var dev_user_name=gps.user_name;
    var param1=user_detail.customize_title1+'：'+user_detail.customize_value1
    var param2=user_detail.customize_title2+'：'+user_detail.customize_value2
    var param3=user_detail.customize_title3+'：'+user_detail.customize_value3

        //信息窗口参数722,1536
      console.log(get_height,get_width)
      var opts = {
        width : 350,     // 信息窗口宽度
        height: 280,     // 信息窗口高度
        };
      var info_window_baidu;
      info_window_baidu=
     "<div style='margin:0;padding:0;border-radius:20px'>"+
      "<table class='layui-table' lay-size='sm'  style='font-size:10px;margin:0px 0px 0px 0px;padding:0px 0px 0px 0px;'>"+
      "<tbody>"+
      "<tr>"+
        "<td colspan=2 bgcolor='#009688' style='height:15px'><font color='white'>"+dev_user_name+','+param1+','+param2+','+param3+"</font></td>"+
      "</tr>"+

      "<tr >"+
      "<td colspan=2 bgcolor='#009688' style='height:15px'><font color='white'>"+"设备ID : "+gps.device_id+"</font></td>"+
      "</tr>"+
      "<tr>"+
      "<td colspan=2>"+
      "<div class='layui-row'>"+
      "<div class='layui-col-lg4'>"+status+"</div>"+
      "<div class='layui-col-lg8'>"+
      "<i class='fa fa-battery-full pull-right' style = 'font-size:10px; padding-right: 9px;color: #009688;' > "+gps.battery+"</i>"+
      "<i class='fa fa-broadcast-tower pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+rssi+"</i>"+
      "<i class='fa fa-satellite-dish pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+gps_num+"</i>"+
      "<i class='fa fa-satellite pull-right'  style = 'font-size:10px; padding-right: 1px;color: #009688;'>"+bds_num+"</i>"+
      "</div>"+
      "</div>"+
      "</td>"+
      "<tr  id='heart_blood'>"+"<td>"+"<i class='fa fa-heartbeat' aria-hidden='true' style='color: red;'></i>："+heart_rate+"次/min</td>"+"<td>"+" <i class='fa fa-stethoscope' aria-hidden='true' style='color: blue;'></i> : "+blood_pres+"</td>"+
      "</tr>"+
       "<tr  id='show_add'>"+"<td>"+"<i class='fa fa-thermometer-empty' aria-hidden='true' style='color:#FFB800'></i>："+stop_time+"C°</td>"+"<td>"+"<i class='fa fa-blind' aria-hidden='true' style='color:#5FB878'></i> : "+gps.dynamic.step_count+"步</td>"+
      "</tr>"+
      "<tr>"+
      "<td>"+" <i class='layui-icon layui-icon-console' aria-hidden='true' style='color:#1E9FFF'></i>："+gps.serv_receive+"</td>"+"<td colspan=2>"+" <i class='fa fa-map-marker' aria-hidden='true' style='color:#5FB878'></i>："+gps.dynamic.track_type+"</td>"+
      "</tr>"+
      "<tr>"+
      "<td colspan=2>"+"<i class='fa fa-map' aria-hidden='true' style='color:#009688'></i>："+dev_loca+"</td>"+
      "</tr>"+

        "</tbody>"+
    "</table>"+ 
      "<br>"+
      "<button class='layui-btn layui-btn-xs' onclick='turn_to_page(\"trail\")'>"+
        '<i class="layui-icon ">&#xe715;</i>'+
        "轨迹"+
      "</button>"+
      "<button class='layui-btn layui-btn-xs ' onclick='set_param("+gps.device_id+","+g_status+")'>"+
        '<i class="layui-icon ">&#xe667;</i>'+
        "报警"+
      "</button>"+
      "<button class='layui-btn layui-btn-xs' onclick='command_modal("+gps.device_id+","+g_status+")'>"+
        '<i class="layui-icon ">&#xe601;</i>'+
        "命令"+
      "</button>"+
      "<button class='layui-btn layui-btn-xs' onclick='device_set_modal("+gps.device_id+","+g_status+")'>"+
        '<i class="layui-icon ">&#xe614;</i>'+
        "设置"+
      "</button>"+
      "<button class='layui-btn layui-btn-xs' onclick='turn_to_page(\"interact\")'>"+
        '<i class="layui-icon ">&#xe64c;</i>'+
        "互动"+
      "</button>"+
    "</div>"
    ;
      var gpsinfoWindow = new BMap.InfoWindow(info_window_baidu, opts);
      map.openInfoWindow(gpsinfoWindow,point);
};


var static_marker_inforwindow=function(obj,point,obj_kind){
  var table_id=obj_kind+obj.id
  var window_content='<br><table id="'+table_id+'" >' + '</table>';
  var opts = {
        width : 450,     
        height: 410,     
        };
  //添加弹框到地图上
  var gpsinfoWindow = new BMap.InfoWindow(window_content, opts);
  map.openInfoWindow(gpsinfoWindow,point);
  var table_data=[]
  var table_cols;
  
  if(obj_kind=='building'){
    var param_set=eval('('+obj.param_set+')')
    table_cols=[
            [{ "title": "建筑名字： " + obj.name, "colspan": 2 },
            { "title": "权限： " + param_set.auth_in, "colspan": 2 },],

            [{ "title": "人数上限： " + param_set.person_limit + "人", "colspan": 2 },
            { "title": "停留上限： " + param_set.time_limit + "分", "colspan": 2 }],

            [{ "title": "建筑明细  " + '(当前:' + '0' + '标签)', "colspan": 4 }],

            [{ field: 'name', title: '名称' },
            { field: 'device_id', title: '编号'},
            // { field: 'department', title: '部门' },
            {field: 'serv_receive', title: '进入时间'},
            {field: 'stop_time', title: '停留时长'}
            ]

            ]
  }else if(obj_kind=='scanner'){
    table_cols=[[{ "title": "设备名称： " + obj.name, "colspan": 2 },{ "title": "设备ID： " + obj.device_id, "colspan": 2 },],
                [{ "title": "设备类型： " +  obj.kind, "colspan": 2 },{ "title": "设备状态： " + obj.status , "colspan": 2 }],
                [{ "title": "运行详情:  ", "colspan": 4 }],
                [{ field: 'device_id', title: '标签编号' },{ field: 'rssi', title: '信号强度' },{field: 'serv_receive', title: '时间'},{field: 'ramark', title: '备注'}]
               ]
  }
  
    setTimeout(function(){table.render({
      elem: '#'+table_id,
      data: table_data,
      id:table_id+'_show',
      height: 360,
      cols: table_cols,
      // limits: [10, 15, 20, 25, 50, 100],
      limit: 10000000,
      // page: true
    });},10)
    
}



 var navigationControl = new BMap.NavigationControl({
    // 靠右上角位置
    anchor: BMAP_ANCHOR_TOP_RIGHT,
    // LARGE类型
    type: BMAP_NAVIGATION_CONTROL_LARGE,
    // 启用显示定位
    enableGeolocation: true,
    offset:new BMap.Size(0,55)
  });
  map.addControl(navigationControl);
  // 添加定位控件

var geolocationControl = new BMap.GeolocationControl();
  geolocationControl.addEventListener("locationSuccess", function(e){
    // 定位成功事件
    var address = '';
    address += e.addressComponent.province;
    address += e.addressComponent.city;
    address += e.addressComponent.district;
    address += e.addressComponent.street;
    address += e.addressComponent.streetNumber;
    alert("当前定位地址为：" + address);
  });
  geolocationControl.addEventListener("locationError",function(e){
    // 定位失败事件
    alert(e.message);
  });
  map.addControl(geolocationControl);